
import { Alert, Tooltip, Steps, Button } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { ExpandOutlined, CompressOutlined } from '@ant-design/icons';
import FullScrenn from '../../../../features/util/fullScreen';
import { mapFactoryByGeoq } from '../../../utils/leaflet';
import styles from './index.module.sass';
import { createFence, editorFenceMarker, editorFencePolyline, fenceMarkerEditor, clickMap, completeFence } from '../../../../base/helper/leaflet';
const { Step } = Steps;
const steps = [
    {
        title: '第一步',
        description: '显示围栏',
    },
    {
        title: '第二步',
        description: '编辑围栏',
    },
    {
        title: '第三步',
        description: '完成并保存围栏',
    },
];
const message = (
    <div>
        <div>1.鼠标点击地图，可添加标记点；</div>
        <div>2.鼠标左键按住标记点不松开,拖动标记点可改变围栏；</div>
        <div>3.鼠标左击标记点可删除此标记点；</div>
    </div>
);


interface Props {
    /**表单数据*/
    value?: any

    /**表单回调 */
    onChange?: Function
}

/**
 * 地图电子围栏 基础组件
 */
const FencePanel: React.FC<Props> = ({
    value,
    onChange
}) => {
    console.debug('FencePanel')
    const [isScreen, setIsScreen] = useState(false);
    const mapRef = useRef(null);
    const [map, setMap] = useState<any>(null);
    const [groupPolygon, setGroupPolygon] = useState<any>(L.layerGroup());
    const [groupMarker, setGroupMarker] = useState<any>(L.layerGroup());
    const [groupPolyline, setGroupPolyline] = useState<any>(L.layerGroup());
    const [newFenceData, setNewFenceData] = useState<any>([]);
    const [current, setCurrent] = useState(0);

    /**初始化地图 */
    useEffect(() => {
        let _map: any;
        if (mapRef) {
            _map = mapFactoryByGeoq(mapRef.current, { isMousePosition: true, isDoubleClickZoom: false, tileLayer: 'community' });
            setMap(_map)
        }
        return () => _map && _map.remove();
    }, [])

    /**根据参数创建电子围栏图层 */
    useEffect(() => {
        if (map && value) {
            if (value.length > 0) { map.setView(value[0], 12); }
            createFence(map, value, setGroupPolygon);
        }
    }, [map, value])

    /**当表单项切换显示隐藏时重置地图 */
    useEffect(() => {
        if (map) {
            map.invalidateSize();
        }
    }, [map, onChange])

    useEffect(() => {
        // console.log('groupPolygon:', groupPolygon)
    }, [groupPolygon]);

    useEffect(() => {
        // console.log('groupMarker:', groupMarker)
    }, [groupMarker]);

    // 下一步
    const next = () => {
        setCurrent((_current: any) => {
            let stepNumber = _current + 1;
            // 显示围栏，点击下一步按钮，
            if (stepNumber === 1) {
                groupPolygon.clearLayers();
                groupMarker.clearLayers();
                groupPolyline.clearLayers();
                editorFenceMarker(map, value, groupMarker, setGroupMarker)
                editorFencePolyline(map, value, groupPolyline, setGroupPolyline)
                clickMap(map, groupPolyline, groupMarker, setGroupPolyline, setGroupMarker)
                fenceMarkerEditor(map, groupPolyline, setGroupPolyline, setGroupMarker, groupMarker)
            }
            // 编辑围栏，点击下一步按钮，
            if (stepNumber === 2) {
                map.off('click');
                groupMarker.clearLayers();
                // console.log('value', JSON.stringify(value))
                let newFenceData = completeFence(map, groupPolyline, groupPolygon, setGroupPolygon)
                // console.log('newFenceData', JSON.stringify(newFenceData))
                setNewFenceData(newFenceData);
                onChange && onChange(newFenceData);
            }
            return stepNumber;
        });
    };

    // 上一步
    const up = () => {
        setCurrent((_current: any) => {
            let stepNumber = _current - 1;
            // 点击上一步按钮，回到显示围栏
            if (stepNumber === 0) {
                map.off('click');
                groupPolygon.clearLayers();
                groupMarker.clearLayers();
                groupPolyline.clearLayers();
                createFence(map, value, setGroupPolygon)
            }
            // 点击上一步按钮，回到编辑围栏
            if (stepNumber === 1) {
                groupPolygon.clearLayers();
                groupMarker.clearLayers();
                groupPolyline.clearLayers();
                editorFenceMarker(map, newFenceData, groupMarker, setGroupMarker)
                editorFencePolyline(map, newFenceData, groupPolyline, setGroupPolyline)
                clickMap(map, groupPolyline, groupMarker, setGroupPolyline, setGroupMarker)
                fenceMarkerEditor(map, groupPolyline, setGroupPolyline, setGroupMarker, groupMarker)
            }
            return stepNumber;
        });
    };

    // 完成并保存围栏
    const prev = () => {
        if (newFenceData.length) setCurrent(current + 1);
    };

    useEffect(() => {
        //初始化地图全屏
        FullScrenn.init(screenChange)
    }, []);

    // 屏幕变化
    const screenChange = (isFull: any) => {
        // console.log('是否全屏', isFull);
        setIsScreen(isFull);
    };

    //地图放大缩小
    function handleOutlined() {
        setIsScreen(val => !val)
        if (isScreen) {
            //退出全屏
            FullScrenn.exitFullScreen();
        } else {
            //进入全屏
            FullScrenn.enterFullScreen();
        }
    }

    return (
        <article>
            <div className={isScreen ? styles.mapBoxMax : styles.mapBox}>
                <div className={styles.map} ref={mapRef}></div>
                <div className={styles.stepsPanel}>
                    <Steps current={current} className={styles.steps}>
                        {steps.map(item => (
                            <Step key={item.title} title={item.title} description={item.description} />
                        ))}
                    </Steps>
                    <div className="stepsAction">
                        {current < 2 && (
                            <Button type="primary" className={styles.stepsActionBtn} onClick={() => next()}>
                                下一步
                            </Button>
                        )}
                        {current === 2 && (
                            <Button className={styles.submit} onClick={() => prev()}>
                                保存
                            </Button>
                        )}
                        {current > 0 && current <= 2 && (
                            <Button type="primary" className={styles.stepsActionBtn} onClick={() => up()}>
                                上一步
                            </Button>
                        )}
                        {current > 2 && (
                            <Alert showIcon type="success" className={styles.alert1} message="围栏绘制完成" />
                        )}
                    </div>
                </div>
                {isScreen ?
                    <Tooltip placement="leftBottom" title='退出全屏'>
                        <ExpandOutlined className={styles.outlined} onClick={handleOutlined} />
                    </Tooltip>
                    :
                    <Tooltip placement="leftBottom" title='全屏显示'>
                        <CompressOutlined className={styles.outlined} onClick={handleOutlined} />
                    </Tooltip>
                }
            </div>
            {current === 1 && (
                <Alert showIcon className={styles.alert} message={message} type="warning" />
            )}
        </article>
    )
}

export default FencePanel;